package com.liqi.web.controller.openapi.middleware;

import java.util.ArrayList;
import java.util.List;

import javax.management.MalformedObjectNameException;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import com.liqi.common.utils.Base64ToMultipartFile;
import com.liqi.device.domain.*;
import com.liqi.device.service.IDvRemoteScreenshotService;
import com.liqi.monitor.dto.GetScreenshotRsp;
import com.liqi.monitor.dto.SaveScreenshotReq;
import com.liqi.web.controller.common.minio.MinIoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.liqi.common.core.controller.BaseController;
import com.liqi.common.core.domain.R;
import com.liqi.common.core.page.TableDataInfo;
import com.liqi.device.service.IDvDeviceService;
import com.liqi.device.service.IDvDriveSdkService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.multipart.MultipartFile;

/**
 * 设备信息接口 用于返回设备各类信息
 * 
 * @author zhongping
 * @date 2022-03-04
 */
@Api(tags = "提供给中间件的接口")
@RestController
@RequestMapping("/openApi/middleware")
public class DeviceInfoController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(DeviceInfoController.class);

	@Autowired
	private IDvDeviceService iDvDeviceService;
	@Autowired
	private IDvDriveSdkService iDvDriveSdkService;
	@Autowired
	private IDvRemoteScreenshotService dvRemoteScreenshotService;

	@Autowired(required = false)
	private MinIoService minIoService;

	/**
	 * 配置列表查询接口
	 */
	@ApiOperation("配置列表查询接口")
	@GetMapping("/queryDeviceList")
	public R<QueryDeviceListRsp> queryDeviceList(@ApiParam("模糊查询条件") @RequestParam String searchValue,
			@ApiParam("分页第几页") @RequestParam String pageNum, @RequestParam @ApiParam("分页一页有多行") String pageSize) {
		startPage();
		List<DvDevice> list = iDvDeviceService.queryDeviceListBysearchValue(searchValue);
		TableDataInfo dataTable = getDataTable(list);

		List<DvDevice> rows = (List<DvDevice>) dataTable.getRows();
		QueryDeviceListRsp queryDeviceListRsp = new QueryDeviceListRsp();
		List<DvDeviceDetail> dvDeviceDetails = new ArrayList<>();
		for (DvDevice device : rows) {
			DvDeviceDetail dvDeviceDto = new DvDeviceDetail();
			BeanUtils.copyProperties(device, dvDeviceDto);
			dvDeviceDetails.add(dvDeviceDto);
		}
		queryDeviceListRsp.setDeviceList(dvDeviceDetails);
		queryDeviceListRsp.setTotal((int) dataTable.getTotal());

		return R.ok(queryDeviceListRsp);
	}

	/**
	 * 配置详细信息查询接口
	 */
	@ApiOperation("配置详细信息查询接口")
	@GetMapping("/queryDeviceDetail")
	public R<QueryDeviceDetailRep> queryDeviceDetail(@ApiParam("设备配置编码") @RequestParam String code,
			@ApiParam("中间件版本(目前不需要该参数)") @RequestParam(required = false) String middlewareVersion) {

		DvDevice dvDevice = iDvDeviceService.selectDvDeviceByCode(code);
		List<DvModuleDetail> moduleDetails = new ArrayList<>();

		DvDeviceDetail deviceDetail = new DvDeviceDetail();
		QueryDeviceDetailRep queryDeviceDetailRep = new QueryDeviceDetailRep();
		if (dvDevice == null) {
			return R.ok("未查询到数据");
		} else {
			BeanUtils.copyProperties(dvDevice, deviceDetail);
			List<DvModule> modules = dvDevice.getModules();
			if (modules != null) {
				for (DvModule module : modules) {
					DvModuleDetail dvModuleDetail = new DvModuleDetail();
					BeanUtils.copyProperties(module, dvModuleDetail);

					DvDriveSdk dvDriveSdk = new DvDriveSdk();
					dvDriveSdk.setAdapterName(module.getAdapterName());
					DvDriveSdk driveSdk = iDvDriveSdkService.selectDvDriveSdkByAdapterName(dvDriveSdk);
					if (driveSdk != null) {
						dvModuleDetail.setAdapterName(driveSdk.getAdapterName());
						dvModuleDetail.setAdapterVersion(driveSdk.getAdapterVersion());
					}
					moduleDetails.add(dvModuleDetail);
				}
			}

			queryDeviceDetailRep.setDevice(deviceDetail);
			queryDeviceDetailRep.setModules(moduleDetails);
		}
		return R.ok(queryDeviceDetailRep);

	}

	/**
	 * 驱动下载
	 * 
	 * @throws MalformedObjectNameException
	 */
	@ApiOperation("驱动下载")
	@GetMapping("/downloadDriver")
	public R<DownloadDriverRsp> downloadDriver(@RequestParam(required = false) @ApiParam("驱动代码") String driveCode,
			@RequestParam @ApiParam("插件库名称") String adapterName, @RequestParam @ApiParam("插件库版本") String adapterVersion,
			HttpServletRequest request) {
		DvDriveSdk dvDriveSdk = new DvDriveSdk();
		dvDriveSdk.setAdapterName(adapterName);
		dvDriveSdk.setAdapterVersion(adapterVersion);
		DvDriveSdk driveSdk = iDvDriveSdkService.selectPackageUrl(dvDriveSdk);
		if (driveSdk == null) {
			return R.ok("没有查询到对应数据");
		}
		String localAddr = request.getServerName() + ":";
		int serverPort = request.getServerPort();
		String packageUrl = driveSdk.getPackageUrl();
		DownloadDriverRsp downloadDriverRsp = new DownloadDriverRsp();
		downloadDriverRsp.setPackageUrl("http://" + localAddr + serverPort + packageUrl);
		downloadDriverRsp.setPackageSha256("");
		return R.ok(downloadDriverRsp);
	}


	/**
	 * 远程截屏
	 *screenshot(0=双屏，1=主屏，2=附屏)
	 */
	@ApiOperation("保存中间件最新的远程截屏")
	@PostMapping("/saveScreenshot")
	public R<GetScreenshotRsp> saveScreenshot(@RequestBody @Valid SaveScreenshotReq saveScreenshotReq) {

		DvRemoteScreenshot remoteScreenshot=new DvRemoteScreenshot();

		try {
			String base64 =saveScreenshotReq.getScreenshot();
			StringBuilder base = new StringBuilder(base64);
			if(saveScreenshotReq.getScreenFlag()==1) {
				base.insert(0,"data:image/jpeg;base64,");
			}else {
				base.insert(0,"data:image/jpeg;base64,");
			}
			final String[] base64Array = base.toString().split(",");
			String dataUir = base64Array[0];
			String data = base64Array[1];


			MultipartFile multipartFile = new Base64ToMultipartFile(data, dataUir);

			String upload = minIoService.upload(multipartFile);

			remoteScreenshot.setDeviceId(saveScreenshotReq.getDeviceId());
			remoteScreenshot.setFileUrl(upload);
			remoteScreenshot.setScreenFlag(saveScreenshotReq.getScreenFlag().toString());
			remoteScreenshot.setCreateBy("admin");
			remoteScreenshot.setStatus(0);
			remoteScreenshot.setMessageCode(saveScreenshotReq.getMessageCode());


			dvRemoteScreenshotService.insertDvRemoteScreenshot(remoteScreenshot);


		} catch (Exception e) {
			return R.fail("未传入正确的ip");
		}

		return R.ok(remoteScreenshot);
	}
}
